package com.authine.cloudpivot.ext.utils.convert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;

import java.util.Collections;
import java.util.List;

public class BOConvert implements ConversionService {


    public BOConvert() {
    }

    @Override
    public boolean canConvert(final Class<?> aClass, final Class<?> aClass1) {
        return false;
    }

    @Override
    public boolean canConvert(final TypeDescriptor typeDescriptor, final TypeDescriptor typeDescriptor1) {
        Class<?> type = typeDescriptor1.getType();
        if (type == SelectorFormat.class) {
            return true;
        } else if (type == List.class) {
            return true;
        }

        return false;
    }

    @Override
    public <T> T convert(final Object o, final Class<T> aClass) {

        if (o == null) {
            return null;
        }

        if (aClass == SelectorFormat.class) {
            return JSON.parseObject(o.toString(), aClass);
        } else if (aClass == List.class) {

            Object parse = JSON.parse(o.toString());

            if (parse instanceof JSONObject) {
                SelectorFormat selectorFormat = JSONObject.toJavaObject((JSON) parse, SelectorFormat.class);
                return (T) Collections.singletonList(selectorFormat);
            } else if (parse instanceof JSONArray) {
                return (T) JSONArray.parseArray(o.toString(), SelectorFormat.class);
            }


        }

        return null;
    }

    @Override
    public Object convert(final Object o, final TypeDescriptor typeDescriptor, final TypeDescriptor typeDescriptor1) {
        if (o == null) {
            return null;
        }
        Class<?> type = typeDescriptor1.getType();
        if (type == SelectorFormat.class) {
            Object o1 = JSON.parseObject(o.toString(), type);
            return o1;
        } else if (type == List.class) {

            Object parse = JSON.parse(o.toString());

            if (parse instanceof JSONObject) {
                SelectorFormat selectorFormat = JSONObject.toJavaObject((JSON) parse, SelectorFormat.class);
                return Collections.singletonList(selectorFormat);
            } else if (parse instanceof JSONArray) {
                if (type == SelectorFormat.class) {
                    return JSONArray.parseArray(o.toString(), SelectorFormat.class);
                }
            }
        }
        return null;
    }
}
